package cn.steel.utils;

/**
 * @author: zhaoyuhan
 * @date: 2025/4/29
 * @description: 接口定义
 */

import cn.steel.domain.entity.User;
import cn.steel.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() &&
                !"anonymousUser".equals(authentication.getPrincipal())) {
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            if (user != null) {
                AuthUser authUser = new AuthUser(user);
                AuthContext.setCurrentUser(request, authUser);

                // 修改为字符串比较
                if ("SUPPLIER".equalsIgnoreCase(user.getRole())) {
                    request.setAttribute("supplierId", user.getId());
                } else if ("BUYER".equalsIgnoreCase(user.getRole())) {
                    request.setAttribute("userId", user.getId());
                }
            }
        }
        return true;
    }
}